package com.ny.demo530;

import com.ny.demo530.Employee;

import java.sql.*;
import java.util.Scanner;

public class EmployeeTo {
    private static final String URL = "jdbc:mysql://localhost:3306/empdb";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("----- 员工信息录入 -----");
        System.out.print("员工编号: ");
        int id = scanner.nextInt();

        System.out.print("姓名: ");
        String name = scanner.next();

        System.out.print("密码: ");
        String pwd = scanner.next();

        System.out.print("年龄: ");
        int age = scanner.nextInt();

        Employee emp = new Employee(id, name, pwd, age);

        try {

            Class.forName("com.mysql.cj.jdbc.Driver");

            try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

                String sql = "INSERT INTO employee(id, name, password, age) VALUES (?, ?, ?, ?)";

                try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                    pstmt.setInt(1, emp.getId());
                    pstmt.setString(2, emp.getName());
                    pstmt.setString(3, emp.getPassword());
                    pstmt.setInt(4, emp.getAge());

                    int rows = pstmt.executeUpdate();

                    if (rows > 0) {
                        System.out.println(" 员工信息保存成功!");
                    } else {
                        System.out.println(" 保存失败");
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            System.err.println("数据库驱动未找到: " + e.getMessage());
        } catch (SQLException e) {
            System.err.println("数据库错误: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }
}